<script lang="ts">
    import { getGravatarFromCurrentUser } from '$api/gravatar.svelte';
    import { getMeQuery } from '$api/usersApi.svelte';
    import ErrorMessage from '$comp/ErrorMessage.svelte';
    import EmailInput from '$comp/form/EmailInput.svelte';
    import TextInput from '$comp/form/TextInput.svelte';
    import Loading from '$comp/Loading.svelte';
    import { H3, Muted } from '$comp/typography';
    import * as Avatar from '$comp/ui/avatar';
    import { Button } from '$comp/ui/button';
    import { Separator } from '$comp/ui/separator';

    const userResponse = getMeQuery();
    const gravatar = getGravatarFromCurrentUser(userResponse);

    const generalError = $derived(userResponse.error?.message as string | undefined);

    async function onSave() {
        // await userResponse.mutate({
        //     full_name: userResponse.data.full_name,
        //     email_address: userResponse.data.email_address,
        // });
    }
</script>

<div class="space-y-6">
    <div>
        <H3>Account</H3>
        <Muted>Manage your account settings and set e-mail preferences.</Muted>
    </div>
    <Separator />

    <Avatar.Root class="h-24 w-24" title="Profile Image">
        {#await gravatar.src}
            <Avatar.Fallback><Loading /></Avatar.Fallback>
        {:then src}
            <Avatar.Image alt="gravatar" {src} />
        {/await}
        <Avatar.Fallback>{gravatar.initials}</Avatar.Fallback>
    </Avatar.Root>
    <Muted>Your avatar is generated by requesting a Gravatar image with the email address below.</Muted>

    <form class="space-y-2" onsubmit={onSave}>
        <ErrorMessage message={generalError}></ErrorMessage>
        {#if userResponse.data}
            <TextInput autocomplete="name" bind:value={userResponse.data.full_name} label="Full Name" name="full_name" problem={userResponse.error} required
            ></TextInput>
            <EmailInput
                autocomplete="email"
                bind:value={userResponse.data.email_address}
                label="Email Address"
                name="email_address"
                problem={userResponse.error}
                required
            ></EmailInput>
        {/if}
        <div class="pt-2">
            <Button type="submit">
                {#if userResponse.isLoading}
                    <Loading class="mr-2" variant="secondary"></Loading> Saving...
                {:else}
                    Save
                {/if}
            </Button>
        </div>
    </form>
</div>
